import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  Timer? _timer;
  int _second = 60;

  @override
  void dispose() {
    super.dispose();

    _cancelTimer();
  }

  void _sendCode() {
    _second = 60;

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _second -= 1;
      });

      if (_second == 0) {
        timer.cancel();
        setState(() {
          _second = 60;
        });
      }
    });
  }

  void _cancelTimer() {
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
    }

    print("object");
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
      },
      child: Material(
        color: Colors.transparent,
        child: Align(
          alignment: const Alignment(0, -0.3),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            width: 300,
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15)),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      "验证码登录",
                      style: TextStyle(fontWeight: FontWeight.w600),
                    ),
                    IconButton(
                        onPressed: () {
                          Get.back();
                        },
                        icon: const Icon(
                          Icons.close,
                          size: 20,
                        ))
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                _phoneWidget(),
                const SizedBox(
                  height: 15,
                ),
                _codeWidget(),
                const SizedBox(
                  height: 20,
                ),
                InkWell(
                  onTap: _loginClick,
                  child: Container(
                    width: 150,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(25),
                        gradient: const LinearGradient(
                            colors: [Color(0xFFED7F18), Color(0xFFFFC48C)],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight)),
                    child: const Text(
                      "登录/注册",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 20,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _loginClick() {
    String _phone = _phoneController.text.trim();
    String code = _codeController.text.trim();

    if (_phone.isEmpty) {
      EasyLoading.showInfo("请输入手机号");
      return;
    }

    if (code.isEmpty) {
      EasyLoading.showInfo("请输入验证码");
      return;
    }

    EasyLoading.show();

    Future.delayed(const Duration(seconds: 2), () {
      if (_phone == "18888888888" && code == "6666") {
        EasyLoading.showSuccess("登录成功");
        SharedPreferences.getInstance().then((value) {
          value.setBool("login", true);
          Get.back(result: true);
        });
      } else {
        EasyLoading.showError("验证码输入有误");
      }
    });
  }

  Widget _phoneWidget() {
    return Container(
      height: 50,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
          color: Colors.grey.shade200, borderRadius: BorderRadius.circular(25)),
      child: TextField(
        controller: _phoneController,
        keyboardType: TextInputType.phone,
        decoration: const InputDecoration(
            hintText: "请输入手机号",
            hintStyle: TextStyle(fontSize: 14),
            contentPadding: EdgeInsets.zero,
            border: OutlineInputBorder(borderSide: BorderSide.none)),
      ),
    );
  }

  Widget _codeWidget() {
    return Container(
      height: 50,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
          color: Colors.grey.shade200, borderRadius: BorderRadius.circular(25)),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _codeController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                  hintText: "请输入验证码",
                  hintStyle: TextStyle(fontSize: 14),
                  contentPadding: EdgeInsets.zero,
                  border: OutlineInputBorder(borderSide: BorderSide.none)),
            ),
          ),
          Container(
            height: 20,
            width: 1,
            color: Colors.grey,
          ),
          InkWell(
            onTap: () {
              if (_second == 60) {
                if (_phoneController.text.isEmpty) {
                  EasyLoading.showInfo("请输入手机号");
                  return;
                }
                _sendCode();
              }
            },
            child: Container(
              width: 90,
              alignment: Alignment.center,
              child: Text(
                _second == 60 ? "发送验证码" : "${_second}s后重新发送",
                style: const TextStyle(fontSize: 12, color: Color(0xFFED7F18)),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Future showLoginPage(BuildContext context) {
  return showDialog(context: context, builder: (_) => LoginPage());
}
